//
//  LXCheckApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/20.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXCheckApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXRemarkTabelViewCell.h"
#import "LXApplyAnnexTableCell.h"
#import "LXChooseManagerViewController.h"
#import "LXCarCheckModel.h"
#import "FuZeRenModel.h"
#import "LXAnnexShowTableViewCell.h"
@interface LXCheckApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;

@property (nonatomic) NSMutableArray *annexAry;
@property (nonatomic) NSMutableArray *annexDataAry;

// 验车类型 1发车  2退车
@property (nonatomic) NSInteger checkType;

// 负责人
@property (nonatomic) NSString *employeId;
@property (nonatomic) FuZeRenModel *fuzeModel;

@end

@implementation LXCheckApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
    if (self.type==1) {
        [self layoutCustomNav:self.view title:@"新增验车"];
    }
    else {
        [self layoutCustomNav:self.view title:@"验车详情"];
    }
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
    [self.tableView registerClass:[LXApplyAnnexTableCell class]
         forCellReuseIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
    [self.tableView registerClass:[LXAnnexShowTableViewCell class]
         forCellReuseIdentifier:NSStringFromClass([LXAnnexShowTableViewCell class])];

    NSDictionary *dic = @{
        @"url":@"upLoad_B",
    };
    self.annexAry = [NSMutableArray array];
    self.annexDataAry = [NSMutableArray array];
    [self.annexAry addObject:dic];
    


    
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    if (self.type==1) {
        [self setBottomViewWithText:@"确认新增"];
    }
//    else {
//        [self setBottomViewWithText:@"确认修改"];
//    }
    
    
    
}
- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    
    
    // 模型为空,说明从车辆详情进入
    if (!ObjectIsEmpty(self.checkModel)) {
        
        
        
        // 车牌号
        [self.loanDic setValue:self.checkModel.carNumber forKey:@"carNumber"];
        
        
       
        
      
        // 修改的时候需要带入数据
        if (self.type==2) {
            // 验车类型
            if (self.checkModel.type==1) {
                [self.loanDic setValue:@"发车" forKey:@"checkType"];
            }
            else if(self.checkModel.type==2) {
                [self.loanDic setValue:@"退车" forKey:@"checkType"];
            }
            else {
                [self.loanDic setValue:@"--" forKey:@"checkType"];
            }
            // 负责人
            self.employeId = self.checkModel.employeId;
            [self.loanDic setValue:[NSString stringWithNull:self.checkModel.employeName] forKey:@"employeName"];
            // 备注
            [self.loanDic setValue:self.checkModel.remark forKey:@"remark"];
            // 里程
            [self.loanDic setValue:self.checkModel.mileage forKey:@"mileage"];

            
            //图片
            for (NSString *url in self.checkModel.pics) {
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,url];
                [self.annexAry insertObject:@{@"url":imageUrl} atIndex:0];
                [self.annexDataAry insertObject:url atIndex:0];
            }
        }
        
    }
    
    

    
    self.data = @[
           @{
               @"title":@"车牌号",
               @"key":@"carNumber",
               @"placeHolder" : @"请输入",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(1000),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*验车类型":@"验车类型",
               @"key":@"checkType",
               @"placeHolder" : @"请选择验车类型",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"maxLength":@(1000),
               @"sel":self.type==1?@"clickCheckTypeAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*负责人":@"负责人",
               @"key":@"employeName",
               @"placeHolder" : @"请选择负责人",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"maxLength":@(20),
               @"sel":self.type==1?@"clickEmployeAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*公里数(Km)":@"公里数(Km)",
               @"key":@"mileage",
               @"placeHolder" : @"请输入公里数",
               @"canEdit":self.type==1?@(YES):@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(7),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"inputType":@(NUM_DECIMAL),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"验车附加图片(最多9张)",
               @"key":@"annex",
               @"value":self.checkModel.pics,
               @"height":self.type==1?@(kComAnnexHeight):@([LXAnnexShowTableViewCell getCellHeightWithDataSource:self.checkModel.pics])
           },

           @{
               @"title":@"备注",
               @"key":@"remark",
               @"canEdit":self.type==1?@(YES):@(NO),
               @"placeHolder" : @"请输入~",
               @"height":self.type==1?@(150):@([NSString remarksHeight:self.checkModel.remark])
           },
         
           
    ];
    
   
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.data count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    if ([dic[@"key"] isEqualToString:@"annex"]&&self.type == 1) {
        return [LXApplyAnnexTableCell getCellHeightWithDataSource:self.annexAry] + 30;
    }
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];

    
    // 保单
    if ([dic[@"key"] isEqualToString:@"annex"] && self.type == 1) {
       
        LXApplyAnnexTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.titleLab.text = dic[@"title"];
        
        [cell reloadAnnexData:self.annexAry WithMaxNum:9];
        

        // 添加图片
        [cell setCallBackTakeAnnex:^(NSInteger num) {
            
            [self.view endEditing:YES];
            [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andMultipleImageBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andSelectedNum:9 - self.annexDataAry.count];
            
        }];
        
        
        // 放大图片
        [cell setCallBackExtendAnnex:^(NSInteger num,id obj) {
            [self.view endEditing:YES];
            LXBigImageView *view = [[LXBigImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) WithShowImageAry:self.annexDataAry];
            [view.scrollView setContentOffset:CGPointMake(ScreenWidth*num, 0) animated:NO];
            [[UIApplication sharedApplication].delegate.window addSubview:view];
            
        }];
        // 删除图片
        [cell setCallBackDeleteAnnex:^(NSInteger num) {
            [self.view endEditing:YES];
            [self.annexAry removeObjectAtIndex:num];
            [self.annexDataAry removeObjectAtIndex:num];
            [self.tableView reloadData];
        }];
        

        return cell;
        
    }
    else if([dic[@"key"] isEqualToString:@"annex"] && self.type == 2){
        LXAnnexShowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXAnnexShowTableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.titleLab.text = @"验车附加图片";
        NSArray *ary = dic[@"value"];
        [cell reloadData:ary];
        
        // 放大图片
        [cell setCallBackExtendAnnex:^(NSInteger num,id obj) {
            LXBigImageView *view = [[LXBigImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) WithShowImageAry:ary];
            [view.scrollView setContentOffset:CGPointMake(ScreenWidth*num, 0) animated:NO];
            [[UIApplication sharedApplication].delegate.window addSubview:view];
            
        }];
       
        
        return cell;
    }
    
    if([dic[@"key"] isEqualToString:@"remark"]){
        LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.textView.placeholder = dic[@"placeHolder"];
        cell.textView.maxLength = 200;
        cell.textView.userInteractionEnabled = [dic[@"canEdit"] doubleValue];
        cell.remarkTitle.text = dic[@"title"];
        cell.textView.text = !StringIsEmpty(self.loanDic[dic[@"key"]])?self.loanDic[dic[@"key"]]:@"无";

        if(self.type==2){
            cell.textView.wordNumLabel.hidden = YES;
        }
        
        [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
            self.loanDic[dic[@"key"]]  = textStr;
        }];
        return cell;
    }
    
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    
    
    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}
#pragma mark -- 选择发车类型
-(void)clickCheckTypeAction{
    
    
    [Tool showSheetTitle:nil msg:nil cancelTitle:@"取消" oneBtnTitle:@"发车" twoBtnTitle:@"退车" cancelHandlerBlock:^{
    } oneHandlerBlock:^{
        self.checkType = 1;
        [self.loanDic setValue:@"发车" forKey:@"checkType"];
        [self.tableView reloadData];
    } twoHandlerBlock:^{
        self.checkType = 2;
        [self.loanDic setValue:@"退车" forKey:@"checkType"];
        [self.tableView reloadData];
    } onVC:self];
    
}
#pragma mark -- 选择负责人
-(void)clickEmployeAction{
    [self.view endEditing:YES];
    
    LXChooseManagerViewController *vc = [[LXChooseManagerViewController alloc] init];
    WEAKSELF
    [vc setToSendValue:^(FuZeRenModel * _Nonnull model) {
        [weakSelf.loanDic setValue:model.realName forKey:@"employeName"];
        weakSelf.employeId = model.ID;
        weakSelf.fuzeModel = model;
        [weakSelf.tableView reloadData];
    }];
    vc.model = self.fuzeModel;
    [self pushToNextController:vc];
}

- (NSArray *)data{
    if (!_data) {
        _data = [[NSArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, ScreenHeight - kViewTopHeight - kComHeight - 5) style:UITableViewStylePlain];
        if (self.type == 2) {
            _tableView.frame = CGRectMake(0, kViewTopHeight, ScreenWidth, ScreenHeight - kViewTopHeight);
        }
        
        _tableView.backgroundColor = ColorWithF7F8FA;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}


#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
    if (StringIsEmpty(self.loanDic[@"checkType"])) {
        showAlert(@"请选择验车类型");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"employeName"])) {
        showAlert(@"请选择负责人");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"mileage"])) {
        showAlert(@"请输入公里数");
        return;
    }
    if ([self.loanDic[@"mileage"] intValue] == 0) {
        showAlert(@"公里数不能小于0公里");
        return;
    }
    
    NSMutableDictionary *dic = @{
        @"carId":self.checkModel.carId, // 所属车辆id
        @"carNumber":self.checkModel.carNumber,// 所属车辆车牌号
        @"type":@(self.checkType),// 验车类型
        @"employeName":self.loanDic[@"employeName"],// 负责人
        @"employeId":self.employeId,// 负责人id
        @"mileage":self.loanDic[@"mileage"],// 公里数
        @"remark":self.loanDic[@"remark"],// 备注
        @"pics":self.annexDataAry
        
    }.mutableCopy;
    
    NSString *url;
    if (self.type==1) {
        url = [NSString stringWithFormat:@"%@",POST_PostAddCarCheck];
    }
    else if (self.type==2) {
        url = [NSString stringWithFormat:@"%@",POST_PostUpdateCarCheck];
        [dic setValue:self.checkModel.ID forKey:@"id"];
    }

    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                if (self.type==1) {
                    showAlert(@"新增验车成功");
                }
                else if (self.type==2) {
                    showAlert(@"修改验车成功");
                }
                
                // carModel 有值说明从详情页进入,返回时须刷新列表
                if (!ObjectIsEmpty(self.checkModel)) {
                    kUserDefaultSetBool(YES, kRefreshStr);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
           
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
   
   
    
    
    
}
-(void)uploadImage:(NSArray *)ary{
    
    [self.annexAry removeLastObject];
    MBProgressHUD *hud = [MBProgressHUD showGif];
        
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
    dispatch_async(queue, ^{
    
    [ary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        [MSNetworkManager postRevertUrl:POST_UploadFile_URL params:@{@"type":@"1"} formData:@[obj] success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,resonseObj[@"url"]];
                [self.annexAry addObject:@{
                    @"url":imageUrl
                }];
                [self.annexDataAry addObject:resonseObj[@"url"]];
                
                if (idx == ary.count-1) {
                    [hud hide];
                    [self.annexAry addObject:@{
                        @"url":@"upLoad_B",
                    }];
                   
                    [self.tableView reloadData];
                }
                dispatch_semaphore_signal(semaphore);
            }
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            dispatch_semaphore_signal(semaphore);
            [hud hide];
        } withShowHud:NO];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        
     }];
    });

}


@end
